package com.work06.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 绛河
 * @date 2023/6/1
 * @apiNote
 */
@Configuration
public class RabbitMQConfig {
    @Value("${sms.queue.name}")
    private String sms;
    @Value("${email.queue.name}")
    private String email;
    @Bean
    public Jackson2JsonMessageConverter converter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定义交换器
     * @return
     */
    @Bean
    public DirectExchange exchange() {
        return new DirectExchange("exchange");
    }

    /**
     * 定义短信队列
     * @return
     */
    @Bean
    public Queue smsQueue() {
        return new Queue(sms);
    }

    /**
     * 定义邮件队列
     * @return
     */
    @Bean
    public Queue emailQueue() {
        return new Queue(email);
    }

    /**
     * 将短信队列和交换器绑定
     * @return
     */
    @Bean
    public Binding smsBinding() {
        return BindingBuilder.bind(smsQueue()).to(exchange()).with("sms");
    }

    /**
     * 将邮件队列和交换器绑定
     * @return
     */
    @Bean
    public Binding emailBinding() {
        return BindingBuilder.bind(emailQueue()).to(exchange()).with("email");
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(converter());
        return rabbitTemplate;
    }
}
